<?php
class Generator_IndexController extends Zend_Controller_Action
{

	public function init()
	{
	
	}

	public function modelAction()
	{		
		//tắt layout
		$this->_helper->layout ()->disableLayout ();
		$this->_helper->viewRenderer->setNoRender ( true );
		
		//tham so chung
		$g_module_name = "admin";
		$module_path = $this->getFrontController ()->getModuleDirectory ( $g_module_name ); //duong dan module để lưu file vào
		$u_g_module_name = str_replace ( "-", " ", $g_module_name );
		$u_g_module_name = ucwords ( $u_g_module_name );
		$u_g_module_name = str_replace ( " ", "", $u_g_module_name ); //tên module đã in hoa trong các khai báo khi code
		

		//lay tat ca bang
		$config = Zend_Db_Table::getDefaultAdapter ()->getConfig ();
		$dbname = $config ['dbname'];
		$sql = "SHOW TABLES FROM {$dbname}";
		$tables = Zend_Db_Table::getDefaultAdapter ()->fetchAll ( $sql );
		foreach ( $tables as $table )
		{
			//tham so chung của bảng
			$table_name = ($table ["Tables_in_{$dbname}"]); //tên bảng
			$primary_field = str_replace ( "tbl_", "", $table_name ) . "_id"; //tên cột làm khóa chính
			$model_name = str_replace ( array ("_", "tbl" ), " ", $table_name );
			$model_name = ucwords ( $model_name );
			$model_name = str_replace ( " ", "", $model_name ); //tên model
			$module_name = str_replace ( "tbl_", "", $table_name );
			$module_name = str_replace ( "_", "-", $module_name );
			$u_module_name = str_replace ( "-", " ", $module_name );
			$u_module_name = ucwords ( $u_module_name );
			$u_module_name = str_replace ( " ", "", $u_module_name );
			
			//lay tat ca cot
			$sql = "SHOW COLUMNS FROM {$table_name}";
			$columns = Zend_Db_Table::getDefaultAdapter ()->fetchAll ( $sql );
			
			//quet tren tat ca cot, lay noi dung cần thiết			
			$tmp_var = "";
			$tmp_get = "";
			$tmp_set = "";
			foreach ( $columns as $column )
			{
				//tham so chung của cột
				$column_name = $column ['Field']; //ten cột
				$column_name2 = ucfirst ( preg_replace ( '/([^A-Z])([A-Z])/', "$1_$2", $column_name ) ); //tên cột trong get set
				$column_type = $column ['Type']; //kiểu dữ liệu của cột
				

				//xu li khai bao bien				
				$tmp_var .= "
	protected \${$column_name};";
				
				//xu li get				
				$tmp_get .= "
				
	public function get{$column_name2}()
	{
		return \$this->{$column_name};
	}";
				
				//xu li set					
				$tmp_set .= "
				
	public function set{$column_name2}(\${$column_name})
	{
		\$this->{$column_name} = ";
				if (strpos ( $column_type, "int(" ) !== false)
				{
					if (strrchr ( $column_name, "_" ) == "_time")
						$tmp_set .= "Itvina_Model_Abstract::settype ( \${$column_name}, Itvina_Model_Abstract::TIME );";
					else
						$tmp_set .= "Itvina_Model_Abstract::settype ( \${$column_name}, Itvina_Model_Abstract::NUMERIC );";
				}
				else
				{
					$tmp_set .= "\${$column_name};";
				}
				$tmp_set .= "
		return \$this;
	}";
				
				//đưa vào mảng mã hằng số, mã nhóm hằng số cần tạo
				$constant_constant_group_code = "module-{$module_name}";
				$constant_code = "column-{$column_name}";
				$constant_code_2 = "column-description-{$column_name}";
				$array_constant_info [] = array ('constant_constant_group_code' => $constant_constant_group_code, 'constant_code' => $constant_code, 'column_name' => $column_name, 'constant_content' => $column_name );
				$array_constant_info [] = array ('constant_constant_group_code' => $constant_constant_group_code, 'constant_code' => $constant_code_2, 'column_name' => $column_name, 'constant_content' => '' );
			}
			
			//nội dung file model chứa thuộc tính
			$attrib_model_html = "<?php
	
class {$u_g_module_name}_Model_Db_{$model_name} extends Itvina_Model_Abstract
{{$tmp_var}{$tmp_get}{$tmp_set}
}";
			
			//duong dan luu file model
			$attrib_model_filename = $module_path . "/models/Db/{$model_name}.php";
			
			//nội dung file model chứa xử lý
			$func_model_html = "<?php
	
class {$u_g_module_name}_Model_{$model_name} extends {$u_g_module_name}_Model_Db_{$model_name}
{
	
}";
			
			//duong dan luu file model
			$func_model_filename = $module_path . "/models/{$model_name}.php";
			
			//nội dung file db table 
			$db_table_html = "<?php

class {$u_g_module_name}_Model_DbTable_{$model_name} extends Zend_Db_Table_Abstract
{
	public \$_name = '{$table_name}';
	public \$_primary = '{$primary_field}';
}";
			
			//duong dan luu file db table				
			$db_table_filename = "$module_path/models/DbTable/{$model_name}.php";
			
			//dua vào mảng nội dung,duong dan cần lưu file
			$array_file_info [] = array ('filename' => $func_model_filename, 'html' => $func_model_html, 'replace' => false );
			$array_file_info [] = array ('filename' => $attrib_model_filename, 'html' => $attrib_model_html, 'replace' => true );
			$array_file_info [] = array ('filename' => $db_table_filename, 'html' => $db_table_html, 'replace' => true );
			
			//dua vào mảng nhóm hằng số
			$constant_group_code = "module-{$module_name}";
			$array_constant_group_info [] = array ('constant_group_code' => $constant_group_code );
		}
		
		//luu file
		foreach ( $array_file_info as $file_info )
			$this->fwrite ( $file_info ['filename'], $file_info ['html'], $file_info ['replace'] );
		
		//tao nhóm constant
		$model_name = "{$u_g_module_name}_Model_ConstantGroup";
		$constant_group = new $model_name ();
		foreach ( $array_constant_group_info as $constant_group_info )
		{
			$constant_group_code = $constant_group_info ['constant_group_code'];
			if (! $constant_group->isExist ( "constant_group_code='{$constant_group_code}'" ))
			{
				$constant_group->constant_group_code = $constant_group_code;
				$constant_group->constant_group_name = "Nhóm hằng số {$constant_group_code}";
				$constant_group->insertBase ();
			}
		}
		
		//tạo hằng số
		$constant_model_name = "{$u_g_module_name}_Model_Constant";
		$constant = new $constant_model_name ();
		foreach ( $array_constant_info as $constant_info )
		{
			$constant_constant_group_code = $constant_info ['constant_constant_group_code'];
			$constant_code = $constant_info ['constant_code'];
			$column_name = $constant_info ['column_name'];
			$constant_content = $constant_info ['constant_content'];
			if (! $constant->isExist ( "constant_code='$constant_code' AND constant_constant_group_code='$constant_constant_group_code'" ))
			{
				$constant->constant_constant_group_code = $constant_constant_group_code;
				$constant->constant_code = $constant_code;
				$constant->constant_content = $constant_content;
				$constant->constant_status = 1;
				$constant->constant_display_type = 3;
				//$constant->constant_name = "Ý nghĩa cột {$column_name}";
				//$constant->constant_note = "Ghi chú ý nghĩa cho cột {$column_name}. Thông tin này sẽ hiển thị trên tiêu đề của trang danh sách, thêm và cập nhật.";
				$constant->insertBase ();
			}
		}
	}

	public function moduleAction()
	{
		//tắt layout
		$this->_helper->layout ()->disableLayout ();
		$this->_helper->viewRenderer->setNoRender ( true );
		
		//lay danh sách các folder module 
		$g_module_name = "admin";
		$u_g_module_name = str_replace ( "-", " ", $g_module_name );
		$u_g_module_name = ucwords ( $u_g_module_name );
		$u_g_module_name = str_replace ( " ", "", $u_g_module_name );
		$modules_path = APPLICATION_PATH . "/modules";
		$module_dirs = new DirectoryIterator ( $modules_path );
		foreach ( $module_dirs as $module_dir )
		{
			//kiểm tra phải là folder và khác folder admin không?
			$module_name = $module_dir->getFilename ();
			if (! $module_dir->isFile () && $module_name != $g_module_name && $module_name != '.' && $module_name != '..')
			{
				//xu li tham so
				$u_module_name = str_replace ( "-", " ", $module_name );
				$u_module_name = ucwords ( $u_module_name );
				$u_module_name = str_replace ( " ", "", $u_module_name );
				
				//tao noi dung file Bootstrap.php
				$boot_html = "<?php

class {$u_module_name}_Bootstrap extends Zend_Application_Module_Bootstrap
{
	protected function _initConfigs()
	{
		\$config = new Zend_Config_Ini ( APPLICATION_PATH . '/modules/{$module_name}/configs/application.ini',  '{$module_name}' );
		Zend_Registry::getInstance ()->set ( '{$module_name}' , \$config );
	}
}";
				
				//tao noi dung file application.ini
				$app_html = "[{$module_name}]
				
				";
				
				//tao noi dung file pagination.phtml	
				$page_html = "<?php echo \$this->partial('index/pagination/pagination.phtml','admin',array(\$this));?>";
				
				//tao folder
				$module_path = APPLICATION_PATH . "/modules/{$module_name}";
				$this->mkdir ( $module_path . "/configs" );
				$this->mkdir ( $module_path . "/controllers" );
				$this->mkdir ( $module_path . "/forms" );
				$this->mkdir ( $module_path . "/views" );
				$this->mkdir ( $module_path . "/views/scripts" );
				$this->mkdir ( $module_path . "/views/scripts/index" );
				
				//tao file Bootstrap.php
				$filename = $module_path . "/Bootstrap.php";
				$this->fwrite ( $filename, $boot_html );
				
				//tao file application.ini
				$filename = $module_path . "/configs/application.ini";
				$this->fwrite ( $filename, $app_html, false );
				
				//tao file application.ini
				$filename = $module_path . "/views/scripts/pagination.phtml";
				$this->fwrite ( $filename, $page_html, false );
			}
		}
	}

	public function mkdir($filename)
	{
		if (! file_exists ( $filename ))
			mkdir ( $filename );
	}

	public function fwrite($filename, $string, $replace = true)
	{
		$fail_msg="FAILED";
		$ok_msg="OK";
		if (! $replace)
			if (file_exists ( $filename ))
				return $fail_msg;
		$fp = fopen ( $filename, 'w' );
		if ($fp)
		{
			$result = fwrite ( $fp, $string );
			if ($result === false)
				return $fail_msg;
			fclose ( $fp );
		}
		else
			return $fail_msg;
		return $ok_msg;
	}

	public function controllerAction()
	{
		//nhan tham so
		$request = $this->_request;
		$g_module_name = "admin";
		$u_g_module_name = str_replace ( "-", " ", $g_module_name );
		$u_g_module_name = ucwords ( $u_g_module_name );
		$u_g_module_name = str_replace ( " ", "", $u_g_module_name );
		
		//tao form
		$form = new Generator_Form_Controller ( $this );
		
		//xu li neu post du lieu
		if ($request->isPost ())
		{
			if ($form->isValid ( $request->getPost () ))
			{
				//lay tham so tu form
				$table_name = $form->getValue ( 'table_name' );
				$module_name = $form->getValue ( 'module_name' );
				$controller_name = $form->getValue ( 'controller_name' );
				$adminAction = $form->getValue ( 'adminAction' );
				$view_index_use_order = $form->getValue ( 'view_index_use_order' );
				$view_index_use_status = $form->getValue ( 'view_index_use_status' );
				$generator_file = $form->getValue ( 'generator_file', array () );
				
				//xu li tham so
				$u_module_name = str_replace ( "-", " ", $module_name );
				$u_module_name = ucwords ( $u_module_name );
				$u_module_name = str_replace ( " ", "", $u_module_name );
				$u_controller_name = str_replace ( "-", " ", $controller_name );
				$u_controller_name = ucwords ( $u_controller_name );
				$u_controller_name = str_replace ( "-", "", $u_controller_name );
				$model_name = str_replace ( array ("_", "tbl" ), " ", $table_name );
				$model_name = ucwords ( $model_name );
				$model_name = str_replace ( " ", "", $model_name );
				
				//lay tat ca cot
				$sql = "SHOW COLUMNS FROM {$table_name}";
				$columns = Zend_Db_Table::getDefaultAdapter ()->fetchAll ( $sql );
				$primary_field = str_replace ( "tbl_", "", $table_name ) . "_id";
				$status_field = str_replace ( "tbl_", "", $table_name ) . "_status";
				$code_field = str_replace ( "tbl_", "", $table_name ) . "_code";
				$name_field = str_replace ( "tbl_", "", $table_name ) . "_name";
				$order_field = str_replace ( "tbl_", "", $table_name ) . "_order";
				
				//xu li noi dung file controller
				$main_object_name = str_replace ( "tbl_", "", $table_name );
				$controller_html = "
<?php

class {$u_module_name}_{$u_controller_name}Controller extends Zend_Controller_Action
{
	protected \$_object;
	
	public function init()
	{
		//tạo đối tượng chính của module
		\$this->_object = new {$u_g_module_name}_Model_{$model_name} ();
		
		//lấy tiêu đề 
		\$this->_helper->common->setCaptions ();
	}
	
	//xem danh sách tất cả 
	public function indexAction()
	{
		//lấy tham số
		\$request = \$this->_request;
		\${$status_field} = \$request->getParam ( '{$status_field}', '' );
		\${$code_field} = \$request->getParam ( '{$code_field}', '' );
		\${$name_field} = \$request->getParam ( '{$name_field}', '' );
		
		//các cột cần lấy dữ liệu
		\$select = \" 
		SELECT";
				foreach ( $columns as $key => $column )
				{
					$column_name = $column ['Field'];
					$controller_html .= "
			";
					$controller_html .= $key > 0 ? ", " : "";
					$controller_html .= "`{$column_name}`";
				}
				$controller_html .= "
		FROM {$table_name} \";
		
		//thiết lập điều kiện lấy dữ liệu
		\$where = \" WHERE 1 \";
		if (\${$status_field} != '')
			\$where .= \" AND `{$status_field}` = '\${$status_field}' \";
		if (\${$code_field} != '')
			\$where .= \" AND `{$code_field}` = '\${$code_field}' \";
		if (\${$name_field} != '')
			\$where .= \" AND `{$name_field}` LIKE '%\${$name_field}%' \";

		//thiết lập thứ tự lấy dữ liệu
		\$order = \$this->_helper->common->getOrderString ( array ('$primary_field DESC' ) );
		
		//lấy dữ liệu
		\$query = \$select . \$where . \$order;
		\$data = \$this->_object->queryBase ( \$query );
		
		//phân trang
		\$this->_helper->common->paginate ( \$data );
		
		//truyền dữ liệu ra view
		\$this->view->{$status_field} = \${$status_field};
		\$this->view->{$code_field} = \${$code_field};
		\$this->view->{$name_field} = \${$name_field};
	}
	
	//kích hoạt/ vô hiệu hóa 1 hoặc nhiều dòng
	public function publishAction()
	{
		\$this->_helper->action->publish ( \$this->_object, '{$status_field}' );
	}
	
	//lưu thứ tự sắp xếp của các dòng
	public function saveOrderAction()
	{
		\$this->_helper->action->saveOrder ( \$this->_object, '{$order_field}' );
	}
	
	//xóa 1 hoặc nhiều dòng
	public function deleteAction()
	{
		\$this->_helper->action->delete ( \$this->_object, 'afterDelete', 'beforeDelete');
	}
	
	//hàm kiểm tra dữ liệu ràng buộc trước khi xóa
	//nếu trả về true thì cho xóa, ngược lại kg cho xóa
	public function beforeDelete()
	{
		return true;
	}
	
	//hàm giải phóng dữ liệu liên quan sau khi xóa
	public function afterDelete()
	{
		
	}
	
	//thêm 1 dòng
	public function insertAction()
	{
		//lấy tham số
		\$request = \$this->_request;
		
		//tạo form
		\$form = new {$u_module_name}_Form_{$model_name}_Insert ( \$this );
		
		//phần xử lí chính
		if (\$request->isPost ()) //khi post giá trị
		{
			if (\$form->isValid ( \$request->getPost () )) //khi giá trị trong form đã được kiểm tra thành công
			{
				\$adminAction = \$form->getValue ( 'adminAction' );
				\${$main_object_name} = new {$u_g_module_name}_Model_{$model_name} ( \$form->getValues () );
				
				//kiểm tra có trùng code không, nếu trùng báo lỗi
				if (\$this->_object->isExist ( '{$code_field}', \${$main_object_name}->{$code_field} ))
				{
					\$form->getElement ( '{$code_field}' )->addError ( \$this->_helper->common->getCaption('{$code_field}').' đã tồn tại.' );
					\$form->markAsError ();
				}
				
				//nếu form không có lỗi
				if (! \$form->isErrors ())
				{
					try
					{
						//insert dòng mới
						\${$main_object_name}->insertBase ();
						
						//thông báo + chuyển hướng trang khi thành công				
						\$this->_helper->flashMessenger ( 'Thêm thành công.' );
						if (\$adminAction == 'save-and-close')
						{
							\$this->_helper->redirector ( 'index', '{$controller_name}', '{$module_name}', array() );
						}
						else if (\$adminAction == 'save-and-new')
						{
							\$this->_helper->redirector ( 'insert', '{$controller_name}', '{$module_name}', array() );
						}
					}
					catch ( Exception \$e )
					{
						
					}
				}
			}
		}
		else //khi vào form lần đầu tiên
		{
		
		}
		
		//truyền dữ liệu ra view
		\$this->view->form = \$form;
	}
	
	//cập nhật 1 dòng
	public function updateAction()
	{
		//lấy tham số
		\$request = \$this->_request;
		\$id = \$request->getParam ( 'id' );
		if (is_array ( \$id ))
			\$id = \$id [count ( \$id ) - 1];
		
		//lấy đối tượng cần cập nhật
		\$first_{$main_object_name} = new {$u_g_module_name}_Model_{$model_name} ();
		\$first_{$main_object_name}->findBase ( \$id );
		
		//tạo form
		\$form = new {$u_module_name}_Form_{$model_name}_Update ( \$this );
		
		//phần xử lí chính
		if (\$request->isPost ()) //khi post giá trị
		{
			if (\$form->isValid ( \$request->getPost () )) //khi giá trị trong form đã được kiểm tra thành công
			{
				\$adminAction = \$form->getValue ( 'adminAction' );
				\${$main_object_name} = new {$u_g_module_name}_Model_{$model_name} ( \$form->getValues () );
				
				//kiểm tra có trùng code không?
				\$exist = \$this->_object->countBase(\"`{$code_field}`='{\${$main_object_name}->{$code_field}}' AND {$primary_field}<>\$id \",0)>0;
				
				//nếu trùng mã báo lỗi
				if(\$exist)
				{
					\$form->getElement ( '{$code_field}' )->addError ( \$this->_helper->common->getCaption('{$code_field}').' đã tồn tại.' );
					\$form->markAsError();
				}
				
				//nếu form không có lỗi
				if (! \$form->isErrors ())
				{
					try
					{
						//update dữ liệu
						\${$main_object_name}->updateBase ( \$id );
						
						//thông báo + chuyển hướng trang khi thành công				
						\$this->_helper->flashMessenger ( 'Cập nhật thành công.' );
						if (\$adminAction == 'apply')
						{
							\$this->_helper->redirector ( 'update', '{$controller_name}', '{$module_name}', array('id'=>\$id) );
						}
						else if (\$adminAction == 'save-and-close')
						{
							\$this->_helper->redirector ( 'index', '{$controller_name}', '{$module_name}', array() );
						}
						else if (\$adminAction == 'save-and-new')
						{
							\$this->_helper->redirector ( 'insert', '{$controller_name}', '{$module_name}', array() );
						}
					}
					catch ( Exception \$e )
					{
						
					}
				}
			}
		}
		else //khi vào form lần đầu tiên
		{
			\$form->populate ( \$first_{$main_object_name}->toArray () );
		}
		
		//truyền dữ liệu ra view
		\$this->view->form = \$form;
	}
}";
				
				//xu li noi dung file view index
				$order_header = $view_index_use_order == 1 ? "<?php echo \$this->partial('index/manage/save-order.phtml', 'admin', array('column'=>'{$order_field}')); ?>" : "<?php echo \$this->partial('index/manage/no-save-order.phtml', 'admin'); ?>";
				$order_body = $view_index_use_order == 1 ? "<?php echo \$this->partial('index/manage/orderer.phtml', 'admin', array(\$row->{$primary_field}, \$row->{$order_field})) ?>" : "
				<td>
					<?php echo \$no;?>
				</td>";
				$status_header = $view_index_use_status == 1 ? "
				<th width='65px'>
					<?php echo \$this->partial('index/manage/header.phtml','admin',array('caption'=>\$this->captions,'column'=>'{$status_field}')); ?>
				</th>" : "";
				$status_body = $view_index_use_status == 1 ? "
				<td class='center'>
					<?php echo \$this->partial('index/manage/publish.phtml','admin', array(\$this->url(array('action' => 'publish')),\$row->{$status_field})); ?>	
				</td>" : "";
				$status_filter = $view_index_use_status == 1 ? "
		<?php echo \$this->partial('index/filter/layout.phtml', 'admin',array (		
			\$this->partial('index/filter/publish.phtml', 'admin',array('name'=>'{$status_field}','value'=>\$this->{$status_field})) 
		 )); ?>" : "";
				$column_count = 6;
				$columns_body = "";
				$columns_header = "";
				foreach ( $columns as $column )
				{
					$column_name = $column ['Field'];
					$column_type = $column ['Type'];
					if ($column_name != $order_field && $column_name != $code_field && $column_name != $primary_field && $column_name != $name_field && $column_name != $status_field)
					{
						if (strpos ( $column_type, "int(" ) !== false)
						{
							if (strrchr ( $column_name, "_" ) == "_time")
							{
								$class = "center";
								$body_cell_content = "<?php echo \$this->partial('index/format/time.phtml','admin',array(\$row->{$column_name})); ?>";
							}
							else
							{
								$class = "right";
								$body_cell_content = "<?php echo \$this->partial('index/format/int.phtml','admin',array(\$row->{$column_name})); ?>";
							}
						}
						else if (strpos ( $column_type, "float" ) !== false || strpos ( $column_type, "double" ) !== false)
						{
							$class = "right";
							$body_cell_content = "<?php echo \$this->partial('index/format/float.phtml','admin',array(\$row->{$column_name})); ?>";
						}
						else
						{
							$class = "left";
							$body_cell_content = "<?php echo \$row->{$column_name}; ?>";
						}
						$header_cell_content = "<?php echo \$this->partial('index/manage/header.phtml','admin',array('caption'=>\$this->captions,'column'=>'{$column_name}')); ?>";
						$columns_body .= "
				<td class='{$class}'>
					{$body_cell_content}
				</td>";
						$columns_header .= "
				<th>
					{$header_cell_content}
				</th>
				";
						$column_count ++;
					}
				}
				$view_index_html = "<!-- thanh toolbar -->
<?php \$this->placeholder('toolbar')->captureStart();?>
<?php echo \$this->partial('index/toolbar/publish.phtml', 'admin') ?>
<?php echo \$this->partial('index/toolbar/unpublish.phtml', 'admin') ?>
<?php echo \$this->partial('index/toolbar/divider.phtml', 'admin') ?>
<?php echo \$this->partial('index/toolbar/new.phtml', 'admin', array(\$this->url(array('action' => 'insert')))) ?>
<?php echo \$this->partial('index/toolbar/edit.phtml', 'admin', array(\$this->url(array('action' => 'update')))) ?>
<?php echo \$this->partial('index/toolbar/divider.phtml', 'admin') ?>
<?php echo \$this->partial('index/toolbar/trash.phtml', 'admin', array(\$this->url(array('action' => 'delete')))) ?>
<?php \$this->placeholder('toolbar')->captureEnd();?>
<!-- / --> 

<form id='adminForm' name='adminForm' method='post' action=''>

	<!-- phần tìm kiếm -->
	<fieldset id='filter-bar' style='height: auto'>
		<?php echo \$this->partial('index/search/layout.phtml', 'admin',array (  	
			 \$this->partial('index/search/search.phtml', 'admin',array('label'=>\$this->captions,'value'=>\$this->{$code_field},'name'=>'{$code_field}')),
			 \$this->partial('index/search/search.phtml', 'admin',array('label'=>\$this->captions,'value'=>\$this->{$name_field},'name'=>'{$name_field}')),
			 \$this->partial('index/search/submit.phtml', 'admin') 
		 )); ?>{$status_filter}		 
	</fieldset>	
	<!-- / -->
	
	<!-- danh sách hiển thị -->
	<div class='clr'> </div>
	<table class='adminlist'>
		<thead>			
			<tr>
				{$order_header}
				<?php echo \$this->partial('index/manage/checkbox-all.phtml', 'admin'); ?>				
				<th>
					<?php echo \$this->partial('index/manage/header.phtml','admin',array('caption'=>\$this->captions,'column'=>'{$code_field}')); ?>
				</th>
				<th>
					<?php echo \$this->partial('index/manage/header.phtml','admin',array('caption'=>\$this->captions,'column'=>'{$name_field}')); ?>
				</th>{$columns_header}{$status_header}
				<th width='65px'>
					Quản lý
				</th>
			</tr>
		</thead>
		<tbody>
		<?php if (count(\$this->paginator) > 0): \$no=0;?>
		<?php foreach (\$this->paginator as \$row): ?>
			<tr class='row<?php echo (\$no++)%2 ?>'>
				{$order_body}
				<?php echo \$this->partial('index/manage/checkbox.phtml', 'admin', array(\$row->{$primary_field})) ?>
				<td>
					<?php echo \$row->{$code_field} ?>
				</td>
				<td>
					<?php echo \$row->{$name_field} ?>
				</td>{$columns_body}{$status_body}
				<td class='center'>				
					<?php echo \$this->partial('index/manage/edit.phtml','admin', array(\$this->url(array('action' => 'update','id'=>\$row->{$primary_field})))); ?>
					<?php echo \$this->partial('index/manage/trash.phtml','admin', array(\$this->url(array('action' => 'delete')))); ?>	
				</td>
			</tr>
		<?php endforeach; ?>
		<?php endif; ?>
		</tbody>
		<tfoot>
			<tr>
				<td colspan='{$column_count}'>
					<div class='container'>
						<?php echo \$this->paginationControl(\$this->paginator) ?>
					</div>
				</td>
			</tr>
		</tfoot>
	</table>
	<!-- / -->
";
				
				//xu li noi dung file form insert
				$form_insert_html = "<?php
class {$u_module_name}_Form_{$model_name}_Insert extends Zend_Form
{
	public function __construct(Zend_Controller_Action \$controller)
	{";
				$str_all_element_name = "";
				foreach ( $columns as $key => $column )
				{
					$column_name = $column ['Field'];
					$column_type = $column ['Type'];
					if ($column_name != $primary_field && $column_name != $order_field && $column_name != $status_field)
					{
						$str_all_element_name .= "
			\${$column_name},";
						if (strpos ( $column_type, "int(" ) !== false)
						{
							if (strrchr ( $column_name, "_" ) == "_time")
							{
								$class = "";
								$element_type = 'text';
								$validator = "";
							}
							else
							{
								$class = "numeric";
								$element_type = 'text';
								$validator = "Float";
							}
						}
						else if (strpos ( $column_type, "float" ) !== false || strpos ( $column_type, "double" ) !== false)
						{
							$class = "numeric";
							$element_type = 'text';
							$validator = "Float";
						}
						else if (strpos ( $column_type, "text" ) !== false)
						{
							$class = "";
							$element_type = 'textarea';
							$validator = "";
						}
						else
						{
							$class = "";
							$element_type = 'text';
							$validator = "";
						}
						$form_insert_html .= $this->createElement ( 'insert', $column_name, $element_type, $class, $validator, "", "", $code_field );
					}
				}
				
				//element trạng thái
				$form_insert_html .= $this->createElement ( 'insert', $status_field, "radio", $class, "", "array(1=>'Kích hoạt',0=>'Vô hiệu')", "1" );
				$str_all_element_name .= "
			\${$status_field},";
				
				$form_insert_html .= "
		\$this->addElements ( array ({$str_all_element_name}
		) );	
		
		\$controller->getHelper ( 'common' )->form ( \$this );
	}
}";
				
				//xu li noi dung file view insert
				$view_insert_html = "<!-- thanh toolbar -->
<?php \$this->placeholder('toolbar')->captureStart();?>
<?php echo \$this->partial('index/toolbar/save-and-close.phtml', 'admin') ?>
<?php echo \$this->partial('index/toolbar/save-and-new.phtml', 'admin') ?>   
<?php echo \$this->partial('index/toolbar/divider.phtml', 'admin') ?>
<?php echo \$this->partial('index/toolbar/cancel.phtml', 'admin') ?>
<?php \$this->placeholder('toolbar')->captureEnd();?> 
<!-- / -->

<!-- nội dung form -->
<?php echo \$this->form ?>
<!-- / -->";
				
				//xu li noi dung file form update
				$form_update_html = "<?php
class {$u_module_name}_Form_{$model_name}_Update extends Zend_Form
{
	public function __construct(Zend_Controller_Action \$controller)
	{";
				$str_all_element_name = "";
				foreach ( $columns as $key => $column )
				{
					$column_name = $column ['Field'];
					$column_type = $column ['Type'];
					if ($column_name != $primary_field && $column_name != $order_field && $column_name != $status_field)
					{
						$str_all_element_name .= "
			\${$column_name},";
						if (strpos ( $column_type, "int(" ) !== false)
						{
							if (strrchr ( $column_name, "_" ) == "_time")
							{
								$class = "";
								$element_type = 'text';
								$validator = "";
							}
							else
							{
								$class = "numeric";
								$element_type = 'text';
								$validator = "Float";
							}
						}
						else if (strpos ( $column_type, "float" ) !== false || strpos ( $column_type, "double" ) !== false)
						{
							$class = "numeric";
							$element_type = 'text';
							$validator = "Float";
						}
						else if (strpos ( $column_type, "text" ) !== false)
						{
							$class = "";
							$element_type = 'textarea';
							$validator = "";
						}
						else
						{
							$class = "";
							$element_type = 'text';
							$validator = "";
						}
						$form_update_html .= $this->createElement ( 'update', $column_name, $element_type, $class, $validator, "", "", $code_field );
					}
				}
				
				//element trạng thái
				$form_update_html .= $this->createElement ( 'insert', $status_field, "radio", $class, "", "array(1=>'Kích hoạt',0=>'Vô hiệu')", "1" );
				$str_all_element_name .= "
			\${$status_field},";
				
				$form_update_html .= "
		\$this->addElements ( array ({$str_all_element_name}
		) );	
		
		\$controller->getHelper ( 'common' )->form ( \$this );
	}
}";
				
				//xu li noi dung file view update
				$view_update_html = "<!-- thanh toolbar -->
<?php \$this->placeholder('toolbar')->captureStart();?>
<?php echo \$this->partial('index/toolbar/apply.phtml', 'admin', 'admin') ?>
<?php echo \$this->partial('index/toolbar/save-and-close.phtml', 'admin') ?>
<?php echo \$this->partial('index/toolbar/save-and-new.phtml', 'admin') ?>   
<?php echo \$this->partial('index/toolbar/divider.phtml', 'admin') ?>
<?php echo \$this->partial('index/toolbar/cancel.phtml', 'admin') ?>
<?php \$this->placeholder('toolbar')->captureEnd();?> 
<!-- / -->

<!-- nội dung form -->
<?php echo \$this->form ?>
<!-- / -->";
				
				/* FORM DETAIL */
				$form_detail_html = "<?php
				

/*
//xem chi tiết 1 dòng	
public function detailAction()
	{
		//lấy tham số
		\$request = \$this->_request;
		\$id = \$request->getParam ( 'id' );
		
		//lấy đối tượng cần cập nhật
		\$this->_object->findBase ( \$id );
		
		//tạo form
		\$form = new {$u_module_name}_Form_{$model_name}_Detail ( \$this );
		
		//đổ dữ liệu vào form 
		\$form->populate ( \$this->_object->toArray () );
		
		//truyền dữ liệu ra view
		\$this->view->form = \$form;
	} 
*/	
			
class {$u_module_name}_Form_{$model_name}_Detail extends Zend_Form
{
	public function __construct(Zend_Controller_Action \$controller)
	{";
				$str_all_element_name = "";
				foreach ( $columns as $key => $column )
				{
					$column_name = $column ['Field'];
					$column_type = $column ['Type'];
					if ($column_name != $primary_field && $column_name != $order_field && $column_name != $status_field)
					{
						$str_all_element_name .= "
			\${$column_name},";
						if (strpos ( $column_type, "int(" ) !== false)
						{
							if (strrchr ( $column_name, "_" ) == "_time")
							{
								$class = "";
								$element_type = 'text';
							}
							else
							{
								$class = "numeric";
								$element_type = 'text';
							}
						}
						else if (strpos ( $column_type, "float" ) !== false || strpos ( $column_type, "double" ) !== false)
						{
							$class = "numeric";
							$element_type = 'text';
						}
						else if (strpos ( $column_type, "text" ) !== false)
						{
							$class = "";
							$element_type = 'textarea';
						}
						else
						{
							$class = "";
							$element_type = 'text';
						}
						$form_detail_html .= $this->createElement ( 'detail', $column_name, $element_type, $class, $validator, "", "", $code_field );
					}
				}
				
				//element trạng thái
				if ($view_index_use_status == 1)
				{
					$form_detail_html .= $this->createElement ( 'detail', $status_field, "radio", "", "", "array(1=>'Kích hoạt',0=>'Vô hiệu')", "1" );
					$str_all_element_name .= "
			\${$status_field},";
				}
				
				$form_detail_html .= "
		\$this->addElements ( array ({$str_all_element_name}
		) );	
		
		\$controller->getHelper ( 'common' )->form ( \$this );
	}
}";
				
				/* VIEW DETAIL */
				$view_detail_html = "<!-- thanh toolbar -->
<?php \$this->placeholder('toolbar')->captureStart();?>
<?php echo \$this->partial('index/toolbar/back.phtml', 'admin') ?>
<?php \$this->placeholder('toolbar')->captureEnd();?> 
<!-- / -->

<!-- nội dung form -->
<?php echo \$this->form ?>
<!-- / -->";
				
				//luu vao file
				if ($adminAction == 'apply')
				{
					//duong dẫn module
					$module_path = $this->getFrontController ()->getModuleDirectory ( $module_name );
					
					//tao folder luu form
					$form_path = "$module_path/forms/{$model_name}";
					$this->mkdir ( $form_path );
					
					//luu file từ danh sách file check chọn 
					$filename_msg = "KẾT QUẢ THỰC HIỆN:<br>";
					foreach ( $generator_file as $string )
					{
						$filename = Zend_Registry::get ( 'generator' )->generator_file->$string;
						eval ( "\$filename=\"$filename\";" );
						$filename_msg .= $filename.": ";
						$filename_msg .= $this->fwrite ( $filename, $$string );
						$filename_msg .= "<br>";
					}
					
					//thong bao
					$form->getElement ( 'view_index_use_status' )->addError ($filename_msg );
				}
				
				//do dữ liệu ra form
				$html = "
				/* CONTROLLER */
" . $controller_html . "
				/* VIEW INDEX */
" . $view_index_html . "
				/* FORM INSERT */
" . $form_insert_html . "
				/* VIEW INSERT */
" . $view_insert_html . "
				/* FORM UPDATE */
" . $form_update_html . "
				/* VIEW UPDATE */
" . $view_update_html;
				$form->getElement ( 'html' )->setValue ( $html );
			}
		}
		
		//truyen view
		$this->view->form = $form;
	}

public function createElement($mode, $column_name, $element_type, $class = "", $validator = "", $options = "", $value = "", $code_field = "")
	{
		$html = "
		//{$column_name}
		\${$column_name}=\$this->createElement ( '{$element_type}', '{$column_name}' )
		->setLabel ( \$controller->getHelper('common')->getCaption('{$column_name}' ))
		->setDescription ( \$controller->getHelper('common')->getDescription('{$column_name}' ))";
		
		if ($validator != "")
			$html .= "
		->addValidator ( '{$validator}' )";
		
		if ($column_name == $code_field)
		{
			if ($mode == "insert")
				$html .= "
		->setRequired(true)";
			else if ($mode == "update" || $mode == "detail")
			{
				if ($class != "")
					$class .= " ";
				$class .= "lock";
			}
		}
		else
		{
			if ($mode == "detail")
			{
				if ($class != "")
					$class .= " ";
				$class .= "lock";
			}
		}
		
		if ($class != "")
			$html .= "
		->setAttrib ( 'class','{$class}' )";
		
		if ($options != "")
			$html .= "
		->setMultiOptions({$options})";
		
		if ($value != "")
			$html .= "
		->setValue({$value})";
		
		$html .= "
		;
		";
		return $html;
	}

	public function constantAction()
	{
		//hiển thị fck
		//$this->view->headScript ()->appendFile ( JS . "ckeditor/ckeditor.js" );
		
		//nhan tham so
		$request = $this->_request;
		$module_name = $request->getParam ( 'module_name' );
		$g_module_name = "admin";
		$u_g_module_name = str_replace ( "-", " ", $g_module_name );
		$u_g_module_name = ucwords ( $u_g_module_name );
		$u_g_module_name = str_replace ( " ", "", $u_g_module_name ); //tên module đã in hoa trong các khai báo khi code
		

		//lay tat ca hang so cua module
		$this->_helper->common->setCaptions ( array(),array($module_name) );
		
		//tao form
		$form = new Generator_Form_Constant ( $this );
		
		//xu li neu post du lieu
		if ($request->isPost ())
		{
			if ($form->isValid ( $request->getPost () ))
			{
				$values = $request->getPost ();
				$constant_model_name = "{$u_g_module_name}_Model_Constant";
				$constant = new $constant_model_name ();
				foreach ( $values as $key => $value )
				{
					$pos = strpos ( $key, "column-description-" );
					if ($pos === false)
						$key = "column-" . substr ( $key, strlen ( 'column' ) );
					$constant->constant_content=$value;
					$constant->updateAllBase ( "constant_code='$key'" );
				}
				$this->_helper->flashMessenger ( "Cập nhật thành công." );
				$this->_helper->redirector ( "constant", "index", "generator", array ("module_name" => $module_name ) );
			}
		}
		
		//truyen tham so ra view
		$this->view->form = $form;
	}

	//ten module: author, book-image,...
//ghi chú module: nhóm kho, hàng hóa,...
//ten table: tbl_author, tbl_book_image,...
//ten controller: admin, index, v-index,...


//modelAction -> moduleAction
}